package com.leesche.zcsp.node.web.controller.wechat.income.accounts;

import com.leesche.zcsp.node.utils.UtilDate;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDeviceBalance;
import com.leesche.zcsp.node.web.model.PubDevicePayDetail;
import com.leesche.zcsp.node.web.model.PubDevicePayDetailStatistics;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by kaider on 2016/10/17.
 */
@Controller
@RequestMapping("/wechat/income/accounts")
public class WechatAccountsController {
    private final static Logger logger = LoggerFactory
            .getLogger(WechatAccountsController.class);

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private PubDevicePayDetailStatisticsService detailStatisticsService;
    @Autowired
    private PubDevicePayDetailService pubDevicePayDetailService;
    @Autowired
    private PubDeviceBalanceService pubDeviceBalanceService;
    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;

    private final static String MAINVIEW = "wechat/income/accounts/mainView";
    private final static String DEVICELISTVIEW = "wechat/income/accounts/deviceListView";

    private final static String THATDAYACCOUNTVIEW = "wechat/income/accounts/deviceThatDayStatisticView";
    private final static String FREQUENCYACCOUNTVIEW = "wechat/income/accounts/deviceFrequencyStatisticView";
    private final static String THATDAYDETAILSVIEW = "wechat/income/accounts/deviceThatDayDetailsView";
    private final static String FREQUENCYDETAILSVIEW = "wechat/income/accounts/deviceFrequencyDetailsView";
    //财务兼机修界面
    private final static String FINANCE_MACHINE_VIEW = "wechat/income/accounts/financeMachineView";


    @RequestMapping(value = {"showView", "/mainView"}, method = RequestMethod.GET)
    public String mainView(Model model) {

        Long adminId = getAdminId();
        Integer userRoleType = privilegeService.getCurrentPrincipal().getNtype();
        String date = UtilDate.getSimpleDate();

        QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
        condition.setUserId(adminId);
        condition.setsDate(date);
        PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findListsByCondition(condition).get(0);

        QueryPubDevicePayDetailStatisticsCondition placeDeviceCondition = new QueryPubDevicePayDetailStatisticsCondition();
        placeDeviceCondition.setUserId(adminId);
        placeDeviceCondition.setsDate(date);
        List<PubDevicePayDetailStatisticsDto> detailStatisticsPlaces = detailStatisticsService.findListsByCondition(placeDeviceCondition);

        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setAdminId(adminId);
        List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
        model.addAttribute("date", date);
        model.addAttribute("detailStatisticsDto", detailStatisticsDto);
        model.addAttribute("detailStatisticsPlaces", detailStatisticsPlaces);
        model.addAttribute("placeList", placeList);
        model.addAttribute("cur", "accounts");

        String goView;
        switch (userRoleType){
            //财务
            case 5:
                goView = FINANCE_MACHINE_VIEW;
                model.addAttribute("financeMachine",0);
                break;
            //财务兼机修
            case 7:
                goView = FINANCE_MACHINE_VIEW;
                model.addAttribute("financeMachine",1);
                break;
            default:
                goView = MAINVIEW;
                break;
        }

        return goView;
    }

    /**
     * 场地账目
     *
     * @param placeId
     * @param model
     * @return
     */
    @RequestMapping(value = "/{placeId}/deviceListView", method = RequestMethod.GET)
    public String deviceListView(
            @PathVariable("placeId") Long placeId,
            Model model
    ) {
        Long adminId = getAdminId();
        String date = UtilDate.getSimpleDate();

        QueryPubDeviceCondition condition = new QueryPubDeviceCondition();
        condition.setAdminId(adminId);
        condition.setPlaceId(placeId);
        List<InfoDeviceDto> deviceList = deviceService.findDeviceList(condition);

        QueryPubDevicePayDetailStatisticsCondition statisticsCondition = new QueryPubDevicePayDetailStatisticsCondition();
        statisticsCondition.setUserId(adminId);
        statisticsCondition.setsDate(date);
        statisticsCondition.setPlaceId(placeId);
        PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);

        QueryPubPlaceCondition placeCondition = new QueryPubPlaceCondition();
        placeCondition.setPlaceId(placeId);
        PubPlaceDto placeDto = placeService.findByCondition(placeCondition);

        List<Long> incomeDetail = detailStatisticsService.findIncomeDetail(statisticsCondition);

        model.addAttribute("placeName", placeDto.getAddress());
        model.addAttribute("detailStatisticsDto", detailStatisticsDto);
        model.addAttribute("incomeDetail", incomeDetail);
        model.addAttribute("deviceList", deviceList);
        model.addAttribute("cur", "accounts");
        return DEVICELISTVIEW;
    }

    /**
     * @param placeName     场地名
     * @param deviceSerial  设备序号
     * @param deviceName    设备名称
     * @param statisticDate 查询时间（如果为空表示“今天”）
     * @return 用户场地下的设备今天或历史上某一天的账目信息
     * @Title: showThatDayAccount
     * @Description: TODO(获取设备某天的账目汇总)
     * @author Jerry
     * @date 2016-10-31 03:13:04
     */
    @RequestMapping(value = "{placeId}/thatdayaccount", method = RequestMethod.GET)
    public String showThatDayAccount(@PathVariable("placeId") Long placeId,@RequestParam String placeName, @RequestParam Long deviceSerial, @RequestParam String deviceName, @RequestParam String statisticDate, Model model) {
        DeviceStatistic ds = null;
        try {
            placeName = URLDecoder.decode(placeName, "UTF-8");
            deviceName = URLDecoder.decode(deviceName, "UTF-8");
            if (statisticDate == null || "".equals(statisticDate)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                statisticDate = dateFormat.format(new Date());
            }

            ds = new DeviceStatistic(placeName, deviceSerial, deviceName, statisticDate);

            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setPlaceId(placeId);
            condition.setDeviceId(deviceSerial);
            condition.setsDate(statisticDate);
            condition.setQueryAll(true);
            List<PubDevicePayDetailStatistics> statistics = detailStatisticsService.findDeviceIncomeAccount(condition);
            if (statistics != null && statistics.size() > 0) {
                PubDevicePayDetailStatistics statistic = statistics.get(0);
                if (statistic != null) {
                    ds.statisticNotMoney(statistic.getGamecoinbalnce(), statistic.getGiftbalance(), statistic.getCoinbalance(), statistic.getIntdata1());
                    ds.statisticTotal(statistic.getCoinmoney(), statistic.getBillmoney(), statistic.getWechatmoney(), statistic.getAlipaymoney());
                    ds.statisticCash(statistic.getOnebalance(), statistic.getFivebalance(), statistic.getTenbalance(), statistic.getTwentybalance(), statistic.getFiftybalance(), statistic.getHundredbalance());
                }
            } else {
                ds.deviceStatisticToZero();
            }
            model.addAttribute("placeid", placeId);
            model.addAttribute("statistic", ds);

        } catch (Exception e) {
            logger.error(e.getMessage());
            if (ds == null) {
                ds = new DeviceStatistic(placeName, deviceSerial, deviceName, statisticDate);
            }
            ds.deviceStatisticToZero();
        } finally {
            return THATDAYACCOUNTVIEW;
        }
    }

    /**
     * @Title: showThatDayDetails
     * @Description: TODO(获取具体场地下，具体设备的某天的流水账目)
     * @author Jerry
     * @date 2016-11-03 12:58:44
     */
    @RequestMapping(value = "{placeId}/thatdaydetails", method = RequestMethod.GET)
    public String showThatDayDetails(@PathVariable("placeId") Long placeId,@RequestParam String placeName, @RequestParam Long deviceSerial, @RequestParam String deviceName, @RequestParam String queryDate, Model model) {

        IncomeDetail incomeDetail = null;

        try {
            placeName = URLDecoder.decode(placeName, "UTF-8");
            deviceName = URLDecoder.decode(deviceName, "UTF-8");
            queryDate = URLDecoder.decode(queryDate, "UTF-8");

            incomeDetail = new IncomeDetail(placeName, deviceSerial, deviceName, queryDate,1 ,new ArrayList<IncomeDetail.IncomeItem>());

            findPubDevicePayDetails(placeId,deviceSerial, queryDate, incomeDetail.getMoreIndex(), incomeDetail);

        } catch (Exception e) {
            logger.error(e.getMessage());
            if (incomeDetail == null) {
                incomeDetail = new IncomeDetail(placeName, deviceSerial, queryDate, deviceName,0, null);
            }
        } finally {
            model.addAttribute("placeid",placeId);
            model.addAttribute("income", incomeDetail);
            return THATDAYDETAILSVIEW;
        }
    }

    /**
     * @Title: showThatDayDetailsMore
     * @Description: TODO( 分批获取某天，设备的详细流水账 )
     * @author Jerry Chan
     * @date 2016-11-07 04:03:47
     * @param deviceSerial 设备ID
     * @param queryDate 查询日期
     * @param moreindex 更多下标
     */
    @ResponseBody
    @RequestMapping(value = "{placeId}/detailsmore" , method = RequestMethod.GET)
    public Map<String,Object> showThatDayDetailsMore(@PathVariable("placeId") Long placeId,final @RequestParam Long deviceSerial,final @RequestParam String queryDate, @RequestParam Integer moreindex){
        try{
            moreindex = moreindex == null ? 1 : moreindex;
            IncomeDetail incomeDetail = new IncomeDetail(deviceSerial,queryDate,moreindex,new ArrayList<IncomeDetail.IncomeItem>());

            findPubDevicePayDetails(placeId,deviceSerial, queryDate, moreindex, incomeDetail);

            if(incomeDetail.getIncomeItems() == null || incomeDetail.getIncomeItems().size() <= 0){
                return WebResult.failure("已经没有更多的数据了！").toMap();
            }

            return WebResult.success().put("income",incomeDetail).toMap();
        }catch (Exception e){
            logger.error(e.getMessage());
            return WebResult.failure(e.getMessage()).toMap();
        }
    }

    private void findPubDevicePayDetails(@RequestParam Long placeSerial,@RequestParam Long deviceSerial, @RequestParam String queryDate, @RequestParam Integer moreindex, IncomeDetail incomeDetail) throws Exception {

        Long adminId = getAdminId();
        QueryPubDevicePayDetailCondition condition = new QueryPubDevicePayDetailCondition();
        condition.setPage(moreindex);
        //每次查询都是20条记录
        condition.setRows(5);
        condition.setPlaceid(placeSerial);
        condition.setDeviceid(deviceSerial);
        condition.setReportTime(queryDate);
        condition.setUserId(adminId);

        List<PubDevicePayDetail> pubDevicePayDetails = pubDevicePayDetailService.findPayDetailByDeviceidAndUploadTime(condition);
        for (PubDevicePayDetail pubDevicePayDetail : pubDevicePayDetails) {
            String typeText = Constants.DetailType.getText(pubDevicePayDetail.getPaytype());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

            IncomeDetail.IncomeItem item = incomeDetail.new IncomeItem(pubDevicePayDetail.getDetailid(), typeText, sdf.format(pubDevicePayDetail.getUploadtime()));
            item.mathematicalTotal(pubDevicePayDetail);
            incomeDetail.getIncomeItems().add(item);
        }
    }


    /**
     * @param deviceSerial 设备的序列号（id）
     * @Title: showAccountDates
     * @Description: TODO(获取具体设备的账目的历史时间)
     * @author Jerry
     * @date 2016-11-03 01:37:57
     */
    @ResponseBody
    @RequestMapping(value = "accountdates", method = RequestMethod.GET)
    public Map<String, Object> showAccountDates(@RequestParam Long deviceSerial) {
        try {
            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setDeviceId(deviceSerial);
            List<PubDevicePayDetailStatistics> statistics = detailStatisticsService.findDeviceIncomeAccount(condition);

            if (statistics == null || statistics.size() <= 0) {
                return WebResult.failure("设备未产生账目数据。").toMap();
            }

            List<StatisticQueryDate> queryDates = new ArrayList<StatisticQueryDate>();
            for (PubDevicePayDetailStatistics statistic : statistics) {
                StatisticQueryDate queryDate = new StatisticQueryDate(statistic.getStatisticsid(), statistic.getUserid(), statistic.getPlaceid(), statistic.getDeviceid(), statistic.getSdate());
                queryDates.add(queryDate);
            }
            return WebResult.success().putRows(queryDates).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return WebResult.failure(e.getMessage()).toMap();
        }
    }

    /**
     * @param placeName    场地名称
     * @param deviceSerial 设备ID
     * @param deviceName   设备名称
     * @Title: showFrequencyAccount
     * @Description: TODO(获取按清零次数的账目汇总)
     * @author Jerry
     * @date 2016-11-03 11:01:34
     */
    @RequestMapping(value = "{placeId}/frequencyaccount", method = RequestMethod.GET)
    public String showFrequencyAccount(@PathVariable("placeId") Long placeId,@RequestParam String placeName, @RequestParam Long deviceSerial, @RequestParam String deviceName, Model model) {
        FrequencyStatistic fs = null;
        try {
            placeName = URLDecoder.decode(placeName, "UTF-8");
            deviceName = URLDecoder.decode(deviceName, "UTF-8");

            QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
            condition.setUserid(getAdminId());
            condition.setPlaceid(placeId);
            condition.setDeviceid(deviceSerial);
            condition.setQueryAll(true);
            List<PubDeviceBalance> deviceBalances = pubDeviceBalanceService.findFrequencyStatisticByDeviceid(condition);

            fs = new FrequencyStatistic(placeName, deviceSerial, deviceName, new ArrayList<FrequencyStatistic.StatisticDetails>(), deviceBalances.size());
            if (deviceBalances != null && deviceBalances.size() > 0) {
                for (PubDeviceBalance deviceBalance : deviceBalances) {
                    Long cashTotal = (deviceBalance.getOnebalance() * 1) + (deviceBalance.getFilebalance() * 5) + (deviceBalance.getTenbalance() * 10) + (deviceBalance.getTwentybalance() * 20) + (deviceBalance.getFiftybalance() * 50) + (deviceBalance.getHundredbalance() * 100);
                    FrequencyStatistic.StatisticDetails sd = fs.new StatisticDetails(deviceBalance.getBalanceid(), deviceBalance.getCoinbalance(), cashTotal, deviceBalance.getWechatbalance(), deviceBalance.getAlipaybalance(), deviceBalance.getGamecoinout(), deviceBalance.getGift(), deviceBalance.getGamecoinbu(), deviceBalance.getBalancetime());
                    fs.getStatisticDetails().add(sd);
                }
            } else {
                FrequencyStatistic.StatisticDetails sd = fs.new StatisticDetails();
                sd.toZero();
                fs.getStatisticDetails().add(sd);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            if (fs == null) {
                fs = new FrequencyStatistic(placeName, deviceSerial, deviceName, null, 0);
                FrequencyStatistic.StatisticDetails sd = fs.new StatisticDetails();
                sd.toZero();
                fs.getStatisticDetails().add(sd);
            }
        } finally {
            model.addAttribute("placeid",placeId);
            model.addAttribute("FrequencyStatistic", fs);
            return FREQUENCYACCOUNTVIEW;
        }
    }

    @RequestMapping(value = "{placeId}/thisandlsatstatistic", method = RequestMethod.GET)
    public String showThisAndLastFrequencyStatistic(@PathVariable("placeId") Long placeId,final @RequestParam Long thisBalanceid, final @RequestParam Long lastBalanceid, @RequestParam final Integer index, @RequestParam String placeName, @RequestParam Long deviceSerial, @RequestParam String deviceName, Model model) {
        FrequencyStatistic fs = null;
        try {

            QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
            condition.setUserid(getAdminId());
            condition.setPlaceid(placeId);
            condition.setQueryAll(true);
            if (index.equals(1)) {
                condition.setBalanceid(thisBalanceid);
            } else {
                List<Long> ids = new ArrayList<Long>();
                if (thisBalanceid != null) {
                    ids.add(thisBalanceid);
                }
                if (lastBalanceid != null) {
                    ids.add(lastBalanceid);
                }
                condition.setBalanceids(ids);
            }

            List<PubDeviceBalance> deviceBalances = pubDeviceBalanceService.findFrequencyStatisticByDeviceid(condition);

            fs = new FrequencyStatistic(URLDecoder.decode(placeName, "UTF-8"), deviceSerial, URLDecoder.decode(deviceName, "UTF-8"), new ArrayList<FrequencyStatistic.StatisticDetails>(), index);
            for (PubDeviceBalance deviceBalance : deviceBalances) {
                //初始化游戏币与礼品的数量
                FrequencyStatistic.StatisticDetails ds = fs.new StatisticDetails(deviceBalance.getGamecoinbu(), deviceBalance.getGamecoin(), deviceBalance.getGift(), deviceBalance.getGamecoinout());
                //封装面额张数
                ds.statisticCash(deviceBalance.getOnebalance(), deviceBalance.getFilebalance(), deviceBalance.getTenbalance(), deviceBalance.getTwentybalance(), deviceBalance.getFiftybalance(), deviceBalance.getHundredbalance());
                //统计小计总额
                ds.statisticSubtotal();
                //统计其他支付方式
                ds.statisticOtherPay(deviceBalance.getCoinbalance(),deviceBalance.getWechatbalance(),deviceBalance.getAlipaybalance());
                ds.setBalanceid(deviceBalance.getBalanceid());
                fs.getStatisticDetails().add(ds);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            if (fs == null) {
                fs = new FrequencyStatistic(placeName, deviceSerial, deviceName, null, 0);
                FrequencyStatistic.StatisticDetails fsd = fs.new StatisticDetails();
                fsd.toZero();
                fs.getStatisticDetails().add(fsd);
            }
        } finally {
            model.addAttribute("placeid",placeId);
            model.addAttribute("frequencyStatistic", fs);
            return FREQUENCYDETAILSVIEW;
        }
    }

    private Long getAdminId(){
        Principal principal = privilegeService.getCurrentPrincipal();
        Long adminId;
        if(principal.getParentid()==1){
            adminId = principal.getUserid();
        }else{
            adminId = principal.getParentid();
        }

        return adminId;
    }

}
